import grails.converters.*;

class ControllerBase {



    // If I just define a property called jspViewResolver, Spring will inject
    // the value for me.
    def jspViewResolver;

    def afterInterceptor = { model, modelAndView ->
        
            def userAgents = request.getHeader('User-Agent');
            if (userAgents != null  && userAgents.contains("Widger")) {
                if (modelAndView != null && modelAndView.getViewName() != null) {
                    def String origviewName    = modelAndView.getViewName();
                    def String widgerViewName  = "${origviewName}-widger";
                    def  widgerView = jspViewResolver.loadView(widgerViewName, java.util.Locale.US);
                    
                    // Cheapo test to see if we have a .gsp view or some othe type of view
                    if (widgerView instanceof org.codehaus.groovy.grails.web.servlet.view.GroovyPageView){
                        modelAndView.view = widgerView;
                    }
             }
        }
    }




    def defaultAction = "list"
    
    def login = {
        session.personId = null
        Person person = Person.authenticate(params.name, params.password)
        if (person) {
            session.personId = person.id
            session.widgetCount = person.widgetCount
        }
        else {
            flash.loginNotice = message(code: 'intercept.invalid.login')
        }
        redirect(url: params.url)
    }
  
    def logout = {
        session.personId = null
        session.widgetId = null
        redirect(controller: 'person', action: 'list')
    }

    def actionMethods() {
        def methods = null
        switch (actionName) {
            case 'login':
                methods = [ 'POST', 'PUT' ]
                break;
            case 'create':
                methods = [ 'GET' ]
                break;
            case 'delete':
                methods = [ 'POST', 'DELETE' ]
                break;
            case 'update':
            case 'save':
                methods = [ 'POST', 'PUT' ]
                break;
        }
        methods
    }

    def validMethod(acceptable) {
        def method = request.method
        acceptable.find { it == method } ? null : message(code: 'Illegal operation')
    }

    def loggedInPerson() {
        if (!session.personId) {
            return message(code: 'intercept.not.loggedin')
        }
        null
    }

    Person sessionPerson() {
        if (session.personId) {
            return Person.get(session.personId)
        }
        null
    }
    

    Widget sessionWidget() {
        if (session.widgetId) {
            return Widget.get(session.widgetId)
        }
        null
    }

    void prepareList() {
        if (!params.max) {
            params.max = 10
        }
        if (!params.order) {
            params.order = "desc"
        }
        if (!params.sort) {
            params.sort = "id"
        }
    }
}
